package com.bwie.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.mapper.TOrderDetailMapper;
import com.bwie.pojo.TOrderDetail;
import com.bwie.pojo.TProd;
import com.bwie.pojo.TbOrder;
import com.bwie.pojo.TbUser;
import com.bwie.service.IUserService;
import com.bwie.service.TbOrderService;
import com.bwie.mapper.TbOrderMapper;
import com.bwie.utils.R;
import com.bwie.vo.PageInfoVo;
import com.bwie.vo.PageOrderVo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.logging.SimpleFormatter;


/**
* @author Yoo19
* @description 针对表【tb_order(订单表)】的数据库操作Service实现
* @createDate 2025-04-21 18:50:53
*/
@Service
@Transactional(rollbackFor = Exception.class)
public class TbOrderServiceImpl extends ServiceImpl<TbOrderMapper, TbOrder>
    implements TbOrderService{

    @Autowired
    private TbOrderMapper tbOrderMapper;
    @Autowired
    RestTemplate restTemplate;
    @Autowired
    IUserService iUserService;
    @Autowired
    TOrderDetailMapper tOrderDetailMapper;
    @Autowired
    HttpServletRequest request;


    @Override
    public R getOrderById(Integer id) {

        TbOrder tbOrder = tbOrderMapper.selectById(id);
        if(tbOrder == null){
            return R.ERROR(404,"订单不存在");
        }
//        String url = "http://localhost:9001/user/index/getUserById/" + tbOrder.getUserId();
//        R r =  restTemplate.postForObject(url,null,R.class);

        R r = iUserService.getUserById(tbOrder.getUserId());

        String u = JSON.toJSONString(r.getData());
        TbUser tbUser = JSON.parseObject(u, TbUser.class);



        tbOrder.setUser(tbUser);
        return R.OK(tbOrder);
    }

    @Override
    public R getOrderList(PageOrderVo pageInfoVo) {

        Page<TbOrder> page = new Page<>(pageInfoVo.getPageNum(), pageInfoVo.getPageSize());
//
//        LambdaQueryWrapper<TbOrder> wrapper = new LambdaQueryWrapper<>();
//        if(StringUtils.isNotEmpty(pageInfoVo.getKeyWord())){
//            wrapper.like(TbOrder::getOrderCode,pageInfoVo.getKeyWord());
//        }
//        if(pageInfoVo.getStatus()!=null){
//            wrapper.like(TbOrder::getOrderStatus,pageInfoVo.getStatus());
//        }
//        wrapper.orderByDesc(TbOrder::getOrderId);
        Page<TbOrder> tbOrderPage = tbOrderMapper.getOrderList(page,pageInfoVo.getKeyWord(),pageInfoVo.getStatus());
        return R.OK(tbOrderPage);
    }

    @Override
    public R addOrder(List<TProd> prodList) {


        String token = request.getHeader("token");
        if(token == null){
            return R.ERROR(404,"请先登陆");
        }

        Claims claims = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody();
        Integer userId = claims.get("userId", Integer.class);

        //生成订单并保存
        TbOrder tbOrder = new TbOrder();
        tbOrder.setOrderStatus(0);

        String code = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + RandomUtil.randomNumbers(6);

        tbOrder.setOrderCode(code);
        tbOrder.setUserId(userId);
        tbOrder.setCreateTime(new Date());


        Double amount = 0.0;
        Integer num =0;
        for (TProd tProd : prodList) {
            amount = amount+tProd.getProdPrice()*tProd.getBuyNum();
            num += tProd.getBuyNum();
        }

        tbOrder.setAmount(amount);
        tbOrder.setProdCount(num);
        tbOrderMapper.insert(tbOrder);
        //保存订单明细
        for (TProd tProd : prodList) {
            TOrderDetail tOrderDetail = new TOrderDetail();
            tOrderDetail.setProdId(tProd.getProdId());
            tOrderDetail.setBuyNum(tProd.getBuyNum());
            tOrderDetail.setProdPrice(tProd.getProdPrice());
            tOrderDetail.setOrderId(tbOrder.getOrderId());

            tOrderDetailMapper.insert(tOrderDetail);
        }

        return R.OK();
    }
}




